window.editJS || (editJS = {
    data: {
        "templateImage": {
            "width": 352 * 2,
            "height": 705 * 2,
            "x": 323 * 2,
            "y": 147 * 2,
            "withMm": 0 * 5.9,
            "heightMm": 0 * 5.9
        },
        "pTemplateParam": 1000 * 2
    },
    options: null,
    type: null,
    coupon: 0,
    init: function () {
        var me = this,
            dpi150 = 5.9,
            dpi300 = 11.811; // 150dip:5.9;300dpi:11.811
        // MESSAGE.template.offset_x=me.data.templateImage.x;
        // MESSAGE.template.offset_y=me.data.templateImage.y;
        // MESSAGE.template.width=me.data.templateImage.width;
        // MESSAGE.template.height=me.data.templateImage.height;
        // MESSAGE.template.if_no_image.bg_width=me.data.pTemplateParam;
        // MESSAGE.template.if_no_image.bg_height=me.data.pTemplateParam;
        // MESSAGE.template.basemap=me.data.templateImage.image;
        // MESSAGE.template.thickness=me.data.templateImage.withMm;
        me.getElement();
        me.options = {
            react: {
                x: MESSAGE.template.offset_x,
                y: MESSAGE.template.offset_y,
                width: MESSAGE.template.width,
                height: MESSAGE.template.height
            },
            mask: {
                width: MESSAGE.template.if_no_image.bg_width,
                height: MESSAGE.template.if_no_image.bg_height,
                // src: "/ravimg?src=" + MESSAGE.template.basemap
                src: STATIC_CONFIG.WWWROOT + MESSAGE.template.basemap
            },
            print: {
                // width: MESSAGE.template.thickness * 11.811,
                // height: MESSAGE.template.thickness * 11.811
                width: MESSAGE.template.widthMm * dpi300,
                height: MESSAGE.template.heightMm * dpi300
            },
            border: {
                top: MESSAGE.template.up_image,
                right: MESSAGE.template.right_image,
                bottom: MESSAGE.template.down_image,
                left: MESSAGE.template.left_image
            },
            pdata: window.location.href.getQueryJson()
        }
        if (me.options.pdata.type == 'diy') {
            new Custom(me.options);
        }
        
        me.DEMO.receiver.val(CommonJs.cookie.get('receiver') || '');
        me.DEMO.mobile.val(CommonJs.cookie.get('mobile') || '');

        me.DEMO.detail.val(CommonJs.cookie.get('addressContont') || '');
        var cookAddress = CommonJs.cookie.get('addressList');
        if (cookAddress) {
            try {
                cookAddress = JSON.parse(decodeURIComponent(cookAddress));
                addAddress.address = cookAddress;
            } catch (e) {}
        }
        me.DEMO.price.text("￥" + MESSAGE.template.origin_price);
        addAddress.init();
        me.verification.Me = me;
    },
    getElement: function () {
        var me = this;
        me.DEMO = {
            price: $("#price"),
            editMaterialbox: $(".edit-material-box"),
            addOrder: $(".add-order"),
            receiver: $("#receiver"),            // 收件人
            remark: $("#remark"),                // 备注
            mobile: $("#mobile"),                // 手机号码
            detail: $("#detail"),                // 详细地址
            counts: $("#counts"),                // 购买数量
            coupon: $("#coupon")                 // 优惠码
        }
    },
    counts: function (type) {
        this.getElement();
        var me = this,
            counts = me.DEMO.counts.val();
        counts = counts ? parseInt(counts) : 1;
        if (type == 'add') {
            counts += 1;
        } else if (type == 'minus') {
            if (counts > 1) {
                counts -= 1;
            }
        } else {
            if (counts <= 1) {
                counts = 1;
            }
        }
        me.DEMO.price.text("￥" + (parseFloat(MESSAGE.template.origin_price)*parseFloat(counts || 1)-me.coupon).toFixed(2));
        // me.DEMO.price.text("￥" + parseFloat(MESSAGE.template.origin_price * parseInt(counts || 1)).toFixed(2));
        me.DEMO.counts.val(counts)
    },
    tabCheck: function (t) {
        var me = this,
            that = $(t);
        me.getElement();
        that.addClass("active").siblings('.tab-item').removeClass('active');
        me.DEMO.editMaterialbox.find(">.tab-item").eq(that.index()).removeClass("hide").siblings('.tab-item').addClass('hide');
    },
    tabCheckItem: function (t) {
        var me = this,
            that = $(t),
            checkNnavTap = that.parents('.check-nav-tap'),
            checkNavList = checkNnavTap.siblings('.check-nav-list').find(' > li.list');
        that.addClass("active").siblings('li').removeClass('active');
        checkNavList.eq(that.index()).removeClass("hide").siblings('li.list').addClass('hide');
    },
    upLoadImg: null,
    upLoadUrl: null,
    SynthesisImg: function () {
        var me = this;
        me.getElement();
        if (me.options.pdata.type == 'diy') {
            /**
             * 合成、上传图片
             */
            var isIOS = /(iphone|ipad)/i.test(navigator.userAgent);
            $(".chartlet-item").removeClass("active");
            // 合并数据
            var data = [];
            var getURL = function (elem) {
                var nodeName = elem.nodeName;

                if (nodeName === "IMG") {
                    if (elem.src !== "") {
                        return elem.src;
                    }
                } else if (nodeName === "DIV") {
                    return elem.querySelector("img").src;
                }
            }
            $(".compose-img").each(function (index, elem) {
                var url = getURL(elem);
                if (url) {
                    var rect = $(elem).data("position"),
                        puData={
                            img: url,
                            width: elem.clientWidth,
                            height: elem.clientHeight,
                            x: elem.offsetLeft + rect.x,
                            y: elem.offsetTop + rect.y,
                            rotate: rect.rotate,
                            scale: rect.scale,
                            zIndex: index
                        };
                    data.push(puData);
                    if (index === 0 && elem.id === "user-image" && isIOS) {
                        EXIF.getData(elem, function () {
                            if (EXIF.getTag(this, 'Orientation') === 6) {
                                data[0].rotate += 90;
                                data[0].reverse = true;
                            }
                        });
                    }
                }
            });
            // 如果没有任何数据
            if (data.length === 0) {
                return;
            }
        }
        // 取消编辑状态
        $(".chartlet-item").removeClass("active");
        // 弹出确认提交框
        var tip = layer.open({
            content: ["警告<br><div class='clearfix-row text-a-l'>" +
            "1:实物颜色略有偏差，介意者慎拍。<br>" +
            "2:请勿上传各种情色，暴力，涉及他人隐私以及任何违反国家政策法规的图片；这类图片丽之工作人员有权取消订单。<br> " +
            "3:你需要对上传图片的版权负责，丽之不承担因此引起的第三方责任和法律风险。<br>" +
            "4:你的设计在提交后不能再修改！确认要提交吗?</div>"].join(''),
            btn: ["确定", "取消"],
            yes: function (index) {
                // 取消编辑状态
                $(".chartlet-item").removeClass("active");
                if (me.options.pdata.type == 'diy') {
                    // 图片合成
                    imageCompose({
                        elem: document.getElementById("edit"),
                        width: me.options.print.width,
                        height: me.options.print.height,
                        data: data
                    }, function (url) {
                        me.upLoadUrl = url;
                        // alert(me.upLoadUrl);
                        // window.location.href=me.upLoadUrl;
                        me.DEMO.addOrder.addClass("show");
                        layer.close(tip);
                    });
                } else {
                    me.DEMO.addOrder.addClass("show");
                    layer.close(tip);
                }
            }
        });
    },
    closeAddOrd: function () {
        var me = this;
        me.upLoadImg = null;
        me.upLoadUrl = null;
        me.DEMO.addOrder.removeClass("show");
    },
    verification: {
        Me: null,
        phone: function () {
            var me = this,
                errorMsg = '',
                box = me.Me.DEMO.mobile.parents(".text-box");
            if (me.Me.DEMO.mobile.nulls()) {
                errorMsg = '请输入手机号';
            } else if (!me.Me.DEMO.mobile.val().isMobile()) {
                errorMsg = '手机号格式不正确';
            }
            if (errorMsg != '') {
                me.Me.error(box, errorMsg, me.phoneTime);
                return false;
            } else {
                box.removeClass('error');
                return true;
            }
        }
    },
    error: function (t, msg, timeName) {
        var me = this,
            that = $(t),
            box = that.hasClass('text-box') ? that : that.parents(".text-box");
        box.attr('data-hint', msg);
        box.addClass('error');
        clearTimeout(timeName);
        timeName = setTimeout(function () {
            box.removeClass('error');
        }, 1000);
    },
    uploadStaus: true,
    upload: function () {
        var me = this,
            status = true;
        if (!me.verification.phone()) {
            status = false;
        }
        if (me.DEMO.receiver.nulls()) {
            me.error(me.DEMO.receiver, '请填写收件人', me.receiverTime);
            status = false;
        }
        if (me.DEMO.detail.nulls()) {
            me.error(me.DEMO.detail, '请填写详细地址', me.receiverTime);
            status = false;
        }
        if (status && me.uploadStaus) {
            me.upLoadImg = layer.open({
                content: "图片上传中...",
                shadeClose: false
            });
            addAddress.getElement();
            me.uploadStaus = false;
            CommonJs.cookie.set('receiver', me.DEMO.receiver.val());
            CommonJs.cookie.set('mobile', me.DEMO.mobile.val());

            CommonJs.cookie.set('addressList', JSON.stringify(addAddress.address));
            CommonJs.cookie.set('addressContont', me.DEMO.detail.val());
            var postData = {
                "user_id": CommonJs.cookie.get('user_id'),
                "counts": me.DEMO.counts.val(),
                "coupon": '',
                "receiver": me.DEMO.receiver.val(),
                "mobile": me.DEMO.mobile.val(),
                "telephone": '',
                "province_id": addAddress.DOEM.province.val(),//"用户所属省ID",
                "province": addAddress.DOEM.province.find("option:selected").text(),//"用户所属省",
                "city_id": addAddress.DOEM.city.val(),//"用户所属城市ID",
                "city": addAddress.DOEM.city.find("option:selected").text(),//"用户所属城市",
                "district_id": addAddress.DOEM.district.val(),//"用户地址所在区县ID",
                "district": addAddress.DOEM.district.find("option:selected").text(),//"用户地址所在区县",
                "detail": me.DEMO.detail.val(),
                "is_default": '0',
                "product_id": me.options.pdata.id,
                "mask_id": '',
                "chartlet_id": '',
                "remark": '',
                "type": me.options.pdata.type,
                "coupon_code": me.DEMO.coupon.val()
            }
            if (me.options.pdata.type == 'diy') {
                postData.content = me.upLoadUrl;
            }
            $.ajax({
                type: "POST",
                url: STATIC_CONFIG.WWWROOT + "/index/index/commitOrder",
                dataType: 'json',
                data: postData,
                success: function (result) {
                    setTimeout(function () {
                        me.uploadStaus = true;
                    },1000);
                    if (result.code == 200) {
                        if(result.message=='free'){
                            layer.open({
                                content: result.imsg,
                                shadeClose: false,
                                time: 2.5
                            });
                            setTimeout(function () {
                                window.location.href = "//wechat.zfpresent.com/order";
                            },2500);
                        }else {
                            window.location.href = "/pay/?package=" + result.message.package;
                        }
                    } else {
                        layer.open({
                            content: result.imsg,
                            shadeClose: false,
                            time: 2.5
                        });
                    }
                    layer.close(me.upLoadImg);
                },
                error: function () {
                    me.uploadStaus = true;
                    layer.close(me.upLoadImg);
                }
            });
        }
    },
    getCoupon:function () {
        var me=this,
            couponVal=me.DEMO.coupon.val();
        me.getElement();
        if(couponVal) {
            $.ajax({
                type: "POST",
                url: STATIC_CONFIG.WWWROOT + "/index/index/getCoupon",
                dataType: 'json',
                data: {
                    coupon_code: couponVal
                },
                success: function (result) {
                    if(result.code==200){
                        me.coupon=parseFloat(result.message.coupon||0);
                        me.DEMO.price.text("￥" + (parseFloat(MESSAGE.template.origin_price)*parseFloat(me.DEMO.counts.val()||1)-me.coupon).toFixed(2));
                    }
                },
                error: function () {
                }
            });
        }else{
            me.coupon=0;
            me.DEMO.price.text("￥" + (parseFloat(MESSAGE.template.origin_price)*parseFloat(me.DEMO.counts.val()||1)-me.coupon).toFixed(2));
        }
    }
});

editJS.init();
